package com.forum.demo.controller;

import com.forum.demo.common.AppResult;
import com.forum.demo.common.ResultCode;
import com.forum.demo.config.AppConfig;
import com.forum.demo.model.Article;
import com.forum.demo.model.UserInfo;
import com.forum.demo.model.response.ArticleResponse;
import com.forum.demo.services.impl.ArticleServiceImpl;
import com.forum.demo.utils.checkFailUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleServiceImpl articleService;

    @PostMapping("/create")
    public AppResult create(HttpServletRequest request, @NonNull Long boardId, @NonNull String title, @NonNull String content) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = new Article();
        article.setUserId(user.getId());
        article.setBoardId(boardId);
        article.setContent(content);
        article.setTitle(title);
        articleService.create(article);
        return AppResult.success();
    }

    @GetMapping("/getAllByBoardId")
    public AppResult<List<ArticleResponse>> getAllByBoardId(@RequestParam(value = "boardId", required = false) Long boardId) {
        List<ArticleResponse> articles = null;
        if (boardId == null) {
            articles = articleService.selectAll();
            return AppResult.success(articles);
        } else {
            articles = articleService.selectAllByBoardId(boardId);
            if (articles == null) {
                articles = new ArrayList<>();
            }
        }
        return AppResult.success(articles);
    }

    @RequestMapping("/details")
    public AppResult<ArticleResponse> getDetails(HttpServletRequest request ,@NonNull Long id) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        if (id <= 0) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        ArticleResponse article = articleService.selectDetailById(id);
        if (article == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if (user.getId() == article.getUserId()) {
            // 标识为作者
            article.setOwn(true);
        }
        // 返回结果
        return AppResult.success(article);
    }

    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                           @RequestParam("id") @NonNull Long id,
                           @RequestParam("title") @NonNull String title,
                           @RequestParam("content") @NonNull String content) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户状态
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.selectById(id);

        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断是不是作者
        if (article.getUserId() != user.getId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用Service
        articleService.modify(id, title, content);
        return AppResult.success();
    }

    @GetMapping ("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,@NonNull Long id) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户状态
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    @GetMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,@NonNull Long id) {
        if (id <= 0) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户状态
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.selectById(id);
        // 校验帖子状态
        if (article == null || article.getDeleteState() == 1) {
            // 帖子已删除
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 校验当前登录的用户是不是作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用Service
        articleService.deleteById(id);
        // 返回操作成功
        return AppResult.success();
    }

    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId (HttpServletRequest request ,
                                                    @RequestParam(value = "userId", required = false) Long userId) {
        // 如果UserId为空，那么从session中获取当前登录的用户Id
        if (userId == null) {
            // 获取Session
            HttpSession session = request.getSession(false);
            // 获取User对象
            UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用Service
        List<Article> articles = articleService.selectByUserId(userId);
        // 返回结果
        return AppResult.success(articles);
    }
}
